package me.numark.fragments;

import android.content.Context;
import android.content.Intent;
import android.graphics.Rect;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.squareup.picasso.Picasso;

import butterknife.ButterKnife;
import butterknife.InjectView;
import me.numark.ChatActivity;
import me.numark.MainActivity;
import me.numark.MyProfileActivity;
import me.numark.NumarkApplication;
import me.numark.R;
import me.numark.SettingActivity;
import me.numark.UsersListActivity;
import me.numark.model.ProfileResponse;
import me.numark.net.BaseResponse;
import me.numark.net.GsonRequest;
import me.numark.net.NetworkConstants;
import me.numark.net.NetworkHelper;
import me.numark.providers.Numa;
import me.numark.utils.Settings;


/**
 * Created by tian on 14-9-18:上午7:44.
 */
public class ProfileFragment extends Fragment implements View.OnClickListener {

    @InjectView(R.id.header)
    View header;

    @InjectView(R.id.back)
    ImageView back;

    @InjectView(R.id.title)
    TextView title;

    @InjectView(R.id.right_image)
    ImageView rightButton;

    @InjectView(R.id.avatar)
    ImageView avatar;

    @InjectView(R.id.name)
    TextView name;

    @InjectView(R.id.follow_count)
    TextView follows;

    @InjectView(R.id.fans_count)
    TextView fans;

//    @InjectView(R.id.follow_label)
//    TextView follows_label;
//
//    @InjectView(R.id.fans_label)
//    TextView fans_label;

    @InjectView(R.id.desc)
    TextView desc;

//    @InjectView(R.id.tabs)
//    PagerSlidingTabStrip tabs;

    @InjectView(R.id.pager)
    ViewPager pager;

//    @InjectView(R.id.follow_button)
//    TextView followButton;
//
//    @InjectView(R.id.message_button)
//    TextView messageButton;

//    @InjectView(R.id.user_info_layout)
//    View userInfoLayout;

    public static final String USER_ID = "user_id";

    private String mUserId;

    private String mNick;

    private String mPic;

    private boolean isMe;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_user_profile, container, false);
        ButterKnife.inject(this, v);
        mUserId = getArguments() == null ? Settings.getUid()
                : getArguments().getString(USER_ID, Settings.getUid());
        isMe = mUserId.equals(Settings.getUid());
        initView();
        return v;
    }

    private void initView() {
        back.setVisibility((getActivity() instanceof MainActivity) ? View.INVISIBLE : View.VISIBLE);
        back.setOnClickListener(this);
        if (isMe) {
            title.setText(R.string.profile);
            rightButton.setImageResource(R.drawable.top_bar_setting_button);
            mNick = Settings.getNick();
            name.setText(mNick);
            desc.setText(Settings.getDescription());
//            userInfoLayout.setVisibility(View.INVISIBLE);
            Picasso.with(getActivity()).load(Settings.getAvatar()).into(avatar);
        } else {
            name.setVisibility(View.INVISIBLE);
            rightButton.setImageResource(R.drawable.icon_more);
//            messageButton.setOnClickListener(this);
//            followButton.setOnClickListener(this);
//            userInfoLayout.setVisibility(View.VISIBLE);
            NumarkApplication.getInstance().getContentResolver()
                    .delete(Numa.FeedColumns.CONTENT_URI, Numa.FeedColumns.FEED_TYPE + "=?",
                            new String[]{Integer.toString(NewsFeedFragment.TYPE_OTHERS)});
        }
        title.setTextColor(getResources().getColor(R.color.white));
        rightButton.setOnClickListener(this);
        ProfileFragmentPageAdapter adapter = new ProfileFragmentPageAdapter();
        pager.setAdapter(adapter);
//        tabs.setViewPager(pager);
        fans.setText("0");
        follows.setText("0");
//        follows_label.setOnClickListener(this);
//        fans_label.setOnClickListener(this);
        follows.setOnClickListener(this);
        fans.setOnClickListener(this);
        getProfile();
    }

    private class ProfileFragmentPageAdapter extends FragmentPagerAdapter {

        public ProfileFragmentPageAdapter() {
            super(getChildFragmentManager());
        }

        @Override
        public Fragment getItem(int i) {
            switch (i) {
                case 0:
                    return getTweetsFragment();
                case 1:
                    return getCommentFragment();
            }
            return null;
        }

        @Override
        public int getCount() {
            return 0;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            switch (position) {
                case 0:
                    return mUserId == null ? getString(R.string.mine)
                            : getString(R.string.recommend);
                case 1:
                    return getString(R.string.comment);
                default:
                    return "";
            }
        }
    }

    private NewsFeedFragment mTweetsFragment;

    private CommentsFragment mCommentFragment;


    private Fragment getCommentFragment() {
        Bundle args = new Bundle();
        args.putString(USER_ID, mUserId);
        if (mCommentFragment == null) {
            mCommentFragment = (CommentsFragment) CommentsFragment
                    .instantiate(getActivity(), CommentsFragment.class.getName(), args);
        }
        return mCommentFragment;

    }

    private Fragment getTweetsFragment() {
        Bundle args = new Bundle();
        args.putInt(NewsFeedFragment.TYPE, NewsFeedFragment.TYPE_OTHERS);
        if (mUserId != null) {
            args.putString(NewsFeedFragment.USER_ID, mUserId);
        }
        if (mTweetsFragment == null) {
            mTweetsFragment = (NewsFeedFragment) NewsFeedFragment
                    .instantiate(getActivity(), NewsFeedFragment.class.getName(), args);
        }
        return null;

    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.right_image:
                if (isMe) {
                    new ManagementPopupWindow().show(header);
                } else {
                    //TODO:
                }
                break;
            case R.id.back:
                getActivity().finish();
                break;
//            case R.id.follow_button:
//                doFollow();
//                break;
//            case R.id.fans_label:
            case R.id.fans_count: {
                Intent intent = new Intent(getActivity(), UsersListActivity.class);
                intent.putExtra(UsersListActivity.EXTRA_USER_UID, mUserId);
                intent.putExtra(UsersListActivity.EXTRA_USER_NICK, mNick);
                intent.putExtra(UsersListActivity.EXTRA_TYPE, UsersListActivity.TYPE_FANS);
                startActivity(intent);
            }
            break;
//            case R.id.follow_label:
            case R.id.follow_count: {
                Intent intent = new Intent(getActivity(), UsersListActivity.class);
                intent.putExtra(UsersListActivity.EXTRA_USER_UID, mUserId);
                intent.putExtra(UsersListActivity.EXTRA_USER_NICK, mNick);
                intent.putExtra(UsersListActivity.EXTRA_TYPE, UsersListActivity.TYPE_FOLLOWERS);
                startActivity(intent);
            }
            break;
            case R.id.message_button: {
                Intent intent = new Intent(getActivity(), ChatActivity.class);
                intent.putExtra(ChatActivity.EXTRA_USER_NICK, mNick);
                intent.putExtra(ChatActivity.EXTRA_USER_AVATAR, mPic);
                intent.putExtra(ChatActivity.EXTRA_USER_UID, mUserId);
                startActivity(intent);
            }
            break;
            default:
                break;
        }
    }

    private void doFollow() {
        String baseUrl = isFollow ? NetworkConstants.UNFOLLOW_URL : NetworkConstants.FOLLOW_URL;
        String url = String.format(baseUrl, Settings.getUid(), mUserId);
        GsonRequest<BaseResponse> request = new GsonRequest<BaseResponse>(url, Request.Method.GET,
                BaseResponse.class, true, null, new Response.Listener<BaseResponse>() {
            @Override
            public void onResponse(BaseResponse response) {
                if (response.ret) {
                    isFollow = !isFollow;
                    setFollowStatus();
                } else {
                    Toast.makeText(getActivity(), response.msg, Toast.LENGTH_SHORT).show();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });
        NetworkHelper.getInstance().addToRequestQueue(request);
        NetworkHelper.getInstance().getRequestQueue().start();
    }

    public class ManagementPopupWindow extends PopupWindow implements View.OnClickListener {

        PopupWindow mWindow;

        View mRootView;

        WindowManager mWindowManager;

        public ManagementPopupWindow() {
            mWindow = new PopupWindow(getActivity());
            mWindow.setTouchInterceptor(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    if (event.getAction() == MotionEvent.ACTION_OUTSIDE) {
                        mWindow.dismiss();
                        return true;
                    }
                    return false;
                }
            });

            mWindowManager = (WindowManager) getActivity().getSystemService(Context.WINDOW_SERVICE);
            LayoutInflater inflater = (LayoutInflater) getActivity()
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            mRootView = inflater.inflate(R.layout.management_popup_window, null);
            mRootView.findViewById(R.id.menu_item_1).setOnClickListener(this);
            mRootView.findViewById(R.id.menu_item_2).setOnClickListener(this);
            mWindow.setContentView(mRootView);
        }

        void preShow() {
            if (mRootView == null) {
                throw new IllegalStateException(
                        "setContentView was not called with a view to " + "display.");
            }
            mWindow.setBackgroundDrawable(new ColorDrawable(getActivity().getResources()
                    .getColor(android.R.color.transparent)));
            mWindow.setWidth(WindowManager.LayoutParams.WRAP_CONTENT);
            mWindow.setHeight(WindowManager.LayoutParams.WRAP_CONTENT);
            mWindow.setTouchable(true);
            mWindow.setFocusable(true);
            mWindow.setOutsideTouchable(true);
            mWindow.setContentView(mRootView);
        }

        public void show(View anchor) {
            preShow();
            int[] location = new int[2];
            anchor.getLocationOnScreen(location);
            Rect anchorRect = new Rect(location[0], location[1], location[0] + anchor.getWidth(),
                    location[1] + anchor
                            .getHeight());

            mRootView.measure(ViewGroup.LayoutParams.WRAP_CONTENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT);
            int rootWidth = mRootView.getMeasuredWidth();
            int yPos = anchorRect.bottom;
            int screenWidth = mWindowManager.getDefaultDisplay().getWidth();
            int xPos = screenWidth - rootWidth - 30;
            mWindow.showAtLocation(anchor, Gravity.NO_GRAVITY, xPos, yPos);
        }

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.menu_item_1:
                    startActivity(new Intent(getActivity(), MyProfileActivity.class));
                    mWindow.dismiss();
                    break;
                case R.id.menu_item_2:
                    startActivity(new Intent(getActivity(), SettingActivity.class));
                    mWindow.dismiss();
                    break;
            }
        }
    }

    private boolean isFollow = false;

    private void getProfile() {
        String url = String.format(NetworkConstants.MY_PROFILE_URL,
                mUserId == null ? Settings.getUid() : mUserId);
        GsonRequest<ProfileResponse> request = new GsonRequest<ProfileResponse>(url,
                Request.Method.GET, ProfileResponse.class, true, null,
                new Response.Listener<ProfileResponse>() {
                    @Override
                    public void onResponse(ProfileResponse response) {
                        fans.setText(getString(R.string.fans_countd, response.data.fans));
                        follows.setText(getString(R.string.follow_count, response.data.follow));
                        if (!response.data.is_mine) {
                            mNick = response.data.nick;
                            title.setText(mNick);
                            name.setText(mNick);
                            desc.setText(response.data.des);
                            Picasso.with(getActivity()).load(response.data.pic).into(avatar);
                            mPic = response.data.pic;
                            isFollow = response.data.is_follow;
                            setFollowStatus();
                        } else {
                            Settings.saveProfile(response.data.toString());
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });
        NetworkHelper.getInstance().addToRequestQueue(request);
        NetworkHelper.getInstance().getRequestQueue().start();
    }

    private void setFollowStatus() {
//        followButton.setText(isFollow ? R.string.followed : R.string.follow);
//        followButton.setCompoundDrawablesWithIntrinsicBounds(
//                isFollow ? R.drawable.icon_been_follow
//                        : R.drawable.icon_add_follow, 0, 0, 0);
    }

}
